####################
# Replication codes for "Does Exposure to Election Fraud Research Undermine Conﬁdence in Elections?"
# 1. Data Cleaning
# Last modified: 2024-03-10
####################

### install packages if not already installed
# install.packages("here")
# install.packages("broom")
# install.packages("tidyverse")

### set working directory here
# setwd("")

library(here)
library(broom)
library(tidyverse)

df <- read_csv(paste(here(),"data/election_fraud_survey.csv", sep="/"))

# create treatment variable for likely v unlikely
df <- df %>% mutate(treat_binary = case_when(grepl("Likely", treatment_group) ~ "Likely", 
                                             grepl("Unlikely", treatment_group) ~ "Unlikely",
                                             TRUE ~ "Control"),
                    treat_binary = factor(treat_binary, levels = c("Control", "Likely", "Unlikely")))

# create moon, moon_bin variables
df <- df %>% mutate(moon = ifelse(Q7.15 %in% c(3, 4), "Support", "Not Support"), 
                    moon_bin = ifelse(Q7.15 %in% c(3, 4), 1, 0)) # 

## Manipulation check variable

df <- df %>% mutate(mcheck = case_when(treatment_group %in% c("Mirae-Unlikely", "Minju-Unlikely") & RC2 == 2 ~ 1,
                                       treatment_group %in% c("Mirae-Likely", "Minju-Likely") & RC2 == 1 ~ 1,
                                       treatment_group == "C" & RC2 == 3 ~ 1,
                                       TRUE ~ 0))


# create prop_fraud variable
df <- df %>% mutate(prop_fraud = coalesce(T1_rand, T2_rand, T3_rand, T4_rand),
                    prop_fraud = ifelse(treatment_group == "C", NA_real_, prop_fraud))

# save
write_csv(df, paste(here(),"data/election_fraud_survey_cleaned.csv", sep="/"))
